from garetjax import config
import urllib2, urllib, json

def get_handler():
    username = config.get('twitter:username')
    password = config.get('twitter:password')
    
    password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
    password_manager.add_password(None, 'http://twitter.com', username, password)
    
    handler = urllib2.HTTPBasicAuthHandler(password_manager)
    return urllib2.build_opener(handler)

def post_to_twitter(text):
    args = urllib.urlencode((
        ('status', text),
    ))
    
    response = get_handler().open('http://twitter.com/statuses/update.json', args);
    update = json.read(response.read())
    response.close()
    
    return update